package com.zzyl.framework.interceptor;

import com.zzyl.common.utils.UserIdThreadLocalUtil;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2025/5/23 19:25
 * @Version 1.0
 */
@Slf4j
@Component
public class McroAppInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("小程序请求进入拦截器");
        //获取token  header
        String token = request.getHeader("authorization");
        log.info("获取到的token:{}",token);
        if(!StringUtils.hasText(token)){
            return false;
        }
        //解析token
        Claims body = tokenService.parseToken(token);
        Integer userId = Integer.parseInt(body.get("id") + "");
        //把用户信息放到线程副本变量中
        UserIdThreadLocalUtil.setUserId(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //销毁
        UserIdThreadLocalUtil.remove();
    }
}